package manage

import (
	"lingc/models"
	"lingc/services"
	"lingc/utils" // 导入 common 包
	"strings"

	"github.com/gin-gonic/gin"
)

// PageAuthGroup 获取所有用户
func PageAuthGroup(c *gin.Context) {

	var dataRequest struct {
		Keyword  string `json:"keyword" form:"keyword"`
		Status   string `json:"status" form:"status"`
		Page     int    `json:"page" form:"page"`
		PageSize int    `json:"pageSize" form:"pageSize"` // Exported field
	}
	// log.Printf("PageUser: %+v", dataRequest)

	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	where := ""
	if dataRequest.Keyword != "" {
		keyword := "%" + dataRequest.Keyword + "%"
		where += " (username like " + keyword + " or realname like " + keyword + ")"
	}
	if dataRequest.Status != "" {
		if where != "" {
			where += " and "
		}
		where += " status = " + dataRequest.Status
	}
	list, page, total, err := services.NewAuthGroupService(utils.MysqlClient).PageAuthGroupList(where, dataRequest.Page, dataRequest.PageSize)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"list": list, "page": page, "total": total})
}

// GetUser 获取用户
func GetAuthGroup(c *gin.Context) {

	var dataRequest struct {
		Keywords string `json:"keywords" form:"keywords"`
		Status   string `json:"status" form:"status"`
	}

	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	where := ""
	if dataRequest.Keywords != "" {
		keyword := "'%" + dataRequest.Keywords + "%'"
		where += "`title` like " + keyword
	}
	if dataRequest.Status != "" {
		if where != "" {
			where += " and "
		}
		where += " status = " + dataRequest.Status
	}

	user, err := services.NewAuthGroupService(utils.MysqlClient).GetAuthGroup(where)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// CreateUser 创建用户
func CreateAuthGroup(c *gin.Context) {

	/**
	Name      string `json:"name"`
	Title     string `json:"title"`
	URL       string `json:"url"`
	URLParam  string `json:"url_param"`
	Icon      string `json:"icon"`
	Type      uint8  `json:"type"`
	APIMethod uint8  `json:"api_method"`
	Rank      uint   `json:"rank"`
	ParentID  uint   `json:"parent_id"`
	AppID     int    `json:"app_id"`
	Status    uint8  `json:"status"`
	*/
	var createRequest struct {
		Title  string `json:"title" form:"title"`
		Status uint8  `json:"status" form:"status"`
		Rules  string `json:"rules" form:"rules"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	user := &models.AuthGroupCreate{
		Title:  createRequest.Title,
		Status: createRequest.Status,
		Rules:  createRequest.Rules,
	}
	user, err := services.NewAuthGroupService(utils.MysqlClient).CreateAuthGroup(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// UpdateUser 更新用户
func UpdateAuthGroup(c *gin.Context) {
	var createRequest struct {
		ID     uint   `json:"id" form:"id"`
		Title  string `json:"title" form:"title"`
		Status uint8  `json:"status" form:"status"`
		Rules  string `json:"rules" form:"rules"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	user := &models.AuthGroupUpdate{
		ID:     createRequest.ID,
		Title:  createRequest.Title,
		Status: createRequest.Status,
		Rules:  createRequest.Rules,
		AppID:  0,
	}
	user, err := services.NewAuthGroupService(utils.MysqlClient).UpdateAuthGroup(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// DeleteUser 删除用户
func DeleteAuthGroup(c *gin.Context) {
	var createRequest struct {
		ID  uint   `json:"id" form:"id"`
		IDs string `json:"ids" form:"ids"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if createRequest.ID == 0 && len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if createRequest.ID != 0 {
		if err := services.NewAuthGroupService(utils.MysqlClient).DeleteAuthGroup(createRequest.ID); err != nil {
			utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
			return
		}
	}
	if len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	idStrs := strings.Split(createRequest.IDs, ",")
	var ids []string
	for _, idStr := range idStrs {
		idStr = strings.TrimSpace(idStr)
		if idStr == "" {
			continue
		}
		ids = append(ids, idStr)
	}
	// Convert IDs slice to a format suitable for batch deletion
	if len(ids) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "No valid IDs provided"})
		return
	}
	if err := services.NewAuthGroupService(utils.MysqlClient).DeleteAuthGroups(ids); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	// ... 这里添加删除用户的逻辑 ...
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"msg": "Delete user"})
}
